package org.vectrics.common.db;



import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.apache.log4j.Logger;
import org.hibernate.Session;



/**
 * @author mmoore
 */

public class JdbcExecute extends JdbcExecuteBase {
	private transient static Logger log = Logger.getLogger(JdbcExecute.class);
	
	public JdbcExecute(Session session) {
		super(session);
	}
	
	public static void execute(Session session, JdbcTarget target) {
		JdbcExecute execute = new JdbcExecute(session);
		execute.doExecute(target);
	}
		
	protected void doExecute(JdbcTarget target) {
		if (log.isDebugEnabled())
			log.debug("execute() called.  Target Class = " + target.getClass().getName());

		//DataSource dataSource = getDataSource(dataSourceJndiName);

		log.debug("execute() called.  getting connection");
		Connection connection = getDBConnection();
		
		ResultSet resultSet = null;
		Statement stmt = null;
		String queryStr = target.getQuery();
		
		if (log.isDebugEnabled())
			log.debug("execute() - query = \r\n" + queryStr);
		
		try {
			log.debug("execute() called.  getting statement");
			stmt = connection.createStatement();
			resultSet = stmt.executeQuery(queryStr);
			log.debug("JdbcExecute() - calling process results on target");
			target.processResults(resultSet);
		}
		catch (ProcessException pe) {
			log.error("JdbcExecute() - ProcessException query = " + queryStr, pe);
		}
		catch (SQLException ae) {
			log.error("JdbcExecute() - SQLException, query = " + queryStr, ae);
		}
		finally {
			/*
			try {
				if (resultSet != null) {
					resultSet.close();
				}
			}
			catch (Exception ex) {
				log.error("Exception closing results set", ex);
			}
			*/
			if (stmt != null) {
				closeStatement(stmt);
			}
			//if (connection != null) {
			//	closeConnection(connection);
			//}
		};
	}
	

}
